package com.exes;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mapper.DocumentDetailMapper;
import com.mapper.DocumentInfoMapper;
import com.mapper.GetDetailProgressMapper;
import com.model.DocumentInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 文章任务详情启动器
 */
@Component
@Slf4j
public class ArticleDetailRunnerStarter {

    @Autowired
    GetDetailProgressMapper getDetailProgressMapper;

    @Autowired
    DocumentDetailMapper documentDetailMapper;

    @Autowired
    DocumentInfoMapper documentInfoMapper;

    ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(8,
            12,
            60,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>());

    public void start() throws InterruptedException {
        // 存在安全隐患，数据过多可能造成内存溢出
//        List<DocumentInfo> documentInfos = getDetailProgressMapper.queryAvailableLink();
//        System.out.println(documentInfos.size());
        List<DocumentInfo> documentInfos = documentInfoMapper.query("2022-9-1", "2022-12-31");
        System.out.println(documentInfos.size());
        int pageSize = 50;
        for(int i = 0; i < documentInfos.size(); i += pageSize){
            log.info("start: (" + i + ", " + (i + pageSize) + ")");
            poolExecutor.submit(new ArticleDetailSummaryRunner(documentInfos.subList(i, Math.min(documentInfos.size(), i + pageSize)), documentDetailMapper, getDetailProgressMapper));
        }
        poolExecutor.awaitTermination(60 * 60, TimeUnit.SECONDS);
    }
}
